package com.ls.demo.http.client.client;

import com.google.gson.Gson;
import lombok.extern.java.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author liShan
 * @date 2019/9/4 3:34
 */
@Component
@Log
public class HttpClientImpl implements HttpClient {

    @Override
    public <E, C> C postForObject(String host, int port, String uri, E msg, Class<C> requestCallback, Map<String, ?> uriVariables) {
        Gson gson = new Gson();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(String.format("http://%s:%s%s", host, port, uri));
        httpPost.setHeader(HttpHeaders.ACCEPT, "application/json");
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        StringEntity entity = new StringEntity(gson.toJson(msg), StandardCharsets.UTF_8);
        httpPost.setEntity(entity);
        CloseableHttpResponse response ;
        try {
            response = httpclient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            log.info("请求URL：" + String.format("http://%s:%s%s", host, port, uri) + ";code："+ code);
            if (code == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return gson.fromJson(jsonString, requestCallback);
            }
            response.close();
            httpclient.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}
